package com.example.spring.ioc.javaconfig;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 注解 Configuration：用户标记一个spring配置类，之前是根据xml启动spring上下文，相当于 xml文件  <beans></beans>
 * 注解 ComponentScan：== <context:component-scan base-package="com.example.spring.ioc.javaconfig" >
 * 注解 PropertySource： 引入外部属性资源文件
 * @author lei yu
 * @date 2024/05/15
 */
@Configuration
@ComponentScan(basePackages = "com.example.spring.ioc.javaconfig")
@PropertySource("classpath:db.properties")
public class IocJavaConfig {

    /*
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="username" value="${mysql.username}"></property>
        <property name="password" value="${mysql.password}"></property>
        <property name="url"  value="${mysql.url}"></property>
        <property name="driverClassName" value="${mysql.driverClassName}"></property>
    </bean>
    */


    @Value("${mysql.driverClass}")
    private String driverClassName;
    @Value("${mysql.url}")
    private String url;
    @Value("${mysql.username}")
    private String username;
    @Value("${mysql.password}")
    private String password;

    @Bean(name = {"dataSource", "dd"})
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
